"""
系统代理管理模块
负责处理系统代理设置的启用和禁用
"""
import subprocess
import logging

# 配置日志
logger = logging.getLogger(__name__)


class SystemProxyManager:
    def __init__(self, config_path='config.yaml'):
        self.network_service = "Wi-Fi"  # 默认网络服务
        self.config_path = config_path
        # 导入ConfigManager来读取配置
        try:
            from ..config.manager import ConfigManager
            self.config_manager = ConfigManager(config_path)
        except ImportError:
            self.config_manager = None
            logger.warning("无法导入ConfigManager，将使用默认端口配置")
        logger.info(f"初始化系统代理管理器，默认网络服务: {self.network_service}, 配置文件: {config_path}")
    
    def get_network_services(self):
        """获取网络服务列表"""
        try:
            result = subprocess.run(['networksetup', '-listallnetworkservices'], 
                                  capture_output=True, text=True)
            services = []
            for line in result.stdout.split('\n')[1:]:  # 跳过第一行说明
                line = line.strip()
                if line and not line.startswith('*'):
                    services.append(line)
            return services
        except:
            return ["Wi-Fi"]
    
    def get_proxy_status(self):
        """获取代理状态"""
        try:
            http_result = subprocess.run(['networksetup', '-getwebproxy', self.network_service], 
                                       capture_output=True, text=True)
            https_result = subprocess.run(['networksetup', '-getsecurewebproxy', self.network_service], 
                                        capture_output=True, text=True)
            
            http_enabled = "Yes" in http_result.stdout
            https_enabled = "Yes" in https_result.stdout
            
            return {
                'http_enabled': http_enabled,
                'https_enabled': https_enabled,
                'network_service': self.network_service
            }
        except:
            return {'http_enabled': False, 'https_enabled': False, 'network_service': self.network_service}
    
    def enable_proxy(self, host=None, port=None):
        """启用系统代理"""
        # 如果没有指定host和port，从配置文件读取
        if host is None or port is None:
            if self.config_manager:
                system_proxy_config = self.config_manager.get_system_proxy_config()
                if host is None:
                    host = system_proxy_config.get('host', '127.0.0.1')
                if port is None:
                    port = system_proxy_config.get('port', 8080)
            else:
                # 没有ConfigManager，使用默认值
                if host is None:
                    host = '127.0.0.1'
                if port is None:
                    port = 8080
        
        try:
            subprocess.run(['networksetup', '-setwebproxy', self.network_service, host, str(port)])
            subprocess.run(['networksetup', '-setsecurewebproxy', self.network_service, host, str(port)])
            subprocess.run(['networksetup', '-setwebproxystate', self.network_service, 'on'])
            subprocess.run(['networksetup', '-setsecurewebproxystate', self.network_service, 'on'])
            logger.info(f"系统代理已启用: {host}:{port}")
            return True
        except Exception as e:
            logger.error(f"启用系统代理失败: {e}")
            return False
    
    def disable_proxy(self):
        """禁用系统代理"""
        try:
            subprocess.run(['networksetup', '-setwebproxystate', self.network_service, 'off'])
            subprocess.run(['networksetup', '-setsecurewebproxystate', self.network_service, 'off'])
            return True
        except:
            return False